import { ServiceException } from './../common/excpetion/serviceException';
import * as Core from '@alicloud/pop-core';
import { ReisHelper } from '../common/redisHelper';

export class AliSMSService {
    private accessKeyId = 'LTAI4FtytKKbudrdJsYig3HM';
    private accessKeySecret = 'BGNoom8RrBKHkyhu5INiLFSTgtHLR4';
    private client;
    private verifyCodeMap: ReisHelper<{
        code: string;
        timespan: number;
    }>;
    constructor() {
        this.client = new Core({
            accessKeyId: this.accessKeyId,
            accessKeySecret: this.accessKeySecret,
            endpoint: 'https://dysmsapi.aliyuncs.com',
            apiVersion: '2017-05-25'
        });
        this.verifyCodeMap = new ReisHelper(14);
    }

    SendVerifyCodeSMS(phone: string) {
        let verifyCode = this.GennerateVerifyCode();
        var params = {
            "RegionId": "cn-hangzhou",
            "PhoneNumbers": phone,
            "SignName": "Coeus",
            "TemplateCode": "SMS_192571908",
            "TemplateParam": `{code:${verifyCode}}`
        }
        var requestOption = {
            method: 'POST'
        };

        return new Promise((resolve, reject) => {
            this.client.request('SendSms', params, requestOption).then((result) => {
                if (result.Code == 'OK') {
                    this.verifyCodeMap.set(phone, {
                        code: verifyCode,
                        timespan: Date.now()
                    })
                    resolve(result);
                }
                else {
                    reject(result.Message);
                }
            }, (ex) => {
                console.log(ex);
                reject(ex);
            })
        })
    }

    async VerifcationCode(phone: string, code: string) {
        let item = await this.verifyCodeMap.get(phone);
        if (!item) {
            throw new ServiceException('无效的验证码！');
        }

        let span = Date.now() - item.timespan;
        if (span > 300000) {
            this.verifyCodeMap.delete(phone);
            throw new ServiceException('验证码已过期！');
        }

        if (code != item.code) {
            throw new ServiceException('验证码错误！');
        }

        this.verifyCodeMap.delete(phone);

        this.verifyCodeMap.forEach((value, key) => {
            let s = Date.now() - value.timespan;
            if (s > 300000) {
                this.verifyCodeMap.delete(key);
            }
        });
    }

    GennerateVerifyCode() {
        let str = '01234567896';
        let r = '';
        for (let i = 0; i < 6; i++) {
            let random = Math.ceil(Math.random() * 10);
            r += str[random];
        }
        console.log(r);
        return r;
    }
}